#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
# @File   : show_test.py
# @Author : yuanwenjin
# @Mail   : xxxx@mail.com
# @Date   : 2020/07/17 13:27:08
# @Docs   : 预处理结果显示
'''

import numpy as np
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt
# from matplotlib.colors import rgb_to_hsv, hsv_to_rgb

def pil_draw(image, rect, color=(255,0,0), width=4):
    '''
    ### Docs: 使用PIL画矩形框, 画完矩形框后, 结果已添加在 image 上了, 可以使用 image.show() 进行显示
    ### Args
        - image: obj, PIL.Image.open()打开的图像
        - rect: list, [x,y,w,h] 矩形框
        - color: tuple, (r,g,b) 颜色
        - width: int, 线宽
    ### Examples:
        rect = [100, 100, 20, 40]
        im = Image.open(image_path)
        pil_draw(im, rect, (255,0,0))
        im.show()
    '''

    img_draw = ImageDraw.Draw(image)
    xy = [(rect[0], rect[1]), (rect[0], rect[1]+rect[3]), (rect[0]+rect[2], rect[1]+rect[3]), (rect[0]+rect[2], rect[1]), (rect[0], rect[1])]
    # ImageDraw.Draw 中只有 PIL.ImageDraw.Draw.line(xy, fill=None, width=0) 可以控制线的宽度!!!
    # xy: [(x, y), (x, y), ...] or [x, y, x, y, ...]
    img_draw.line(xy, fill=color, width=width)

annotation_train = '../../get_samples/papilla/for_yolov4_keras/papilla_label_20200616.txt'
with open(annotation_train) as f:
    annotation_line = f.readlines()
for line in annotation_line[:5]:
    print(line[:-1])

input_shape = (608, 608)
hue = 0.1
sat = 1.5
val = 1.5

h, w = input_shape

min_offset_x = 0.4
min_offset_y = 0.4
scale_low = 1 - min(min_offset_x, min_offset_y)
scale_high = scale_low + 0.2
print('scale range: {}, {}'.format(scale_low, scale_high))

place_x = [0, 0, int(w*min_offset_x), int(w*min_offset_x)]
place_y = [0, int(h*min_offset_y), int(w*min_offset_y), 0]

for line in annotation_line[:1]:
    # 测试前面4个数据
    line_content = line.split()
    # 打开图片
    image = Image.open(line_content[0])
    image = image.convert("RGB")
#     plt.imshow(image)
    # 图片的大小
    iw, ih = image.size
    # 保存框的位置
    box = np.array([np.array(list(map(int,box.split(',')))) for box in line_content[1:]])
#     print('image size(h*w): {}*{}, boxes: {}'.format(ih, iw, box))

    # 是否翻转图片
    # flip = rand()<.5
    flip = True
    if flip and len(box)>0:
        plt.subplot(121)
        plt.imshow(image)
        im_show = image.crop((0,0,iw,ih))
        rect = [box[0, 0], box[0, 1], box[0, 2]-box[0, 0], box[0, 3]-box[0, 1]]
        pil_draw(im_show, rect, (0,255,0))
        plt.imshow(im_show)
        plt.subplot(122)
        image = image.transpose(Image.FLIP_LEFT_RIGHT)
        box[:, [0,2]] = iw - box[:, [2,0]]
        im_show = image.crop((0,0,iw,ih))
        rect = [box[0, 0], box[0, 1], box[0, 2]-box[0, 0], box[0, 3]-box[0, 1]]
        pil_draw(im_show, rect, (0,255,0))
        plt.imshow(im_show)
        plt.savefig('image.png')
        plt.show()
        print('image size(h*w): {}*{}, rect: {}'.format(ih, iw, rect))

